package com.yue.yadmin.utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Properties;

import org.apache.commons.lang.StringUtils;

/**
 * 配置文件工具类
 * @author liaoxinyue
 * 2018年7月11日 下午3:23:09
 *
 */
public class PropertiesUtils {
	private static Properties applicationProperties;
	private static synchronized Properties getApplicationProperties(){
		if(applicationProperties==null){
			applicationProperties = new Properties();
			InputStream in = null;
			try {
				in = PropertiesUtils.class.getResourceAsStream("/application.properties");
				if(in!=null)applicationProperties.load(in);
				Log.getLogger(PropertiesUtils.class).debug("applicationProperties:{}",applicationProperties);
			} catch (IOException e) {
				Log.getLogger(PropertiesUtils.class).error("applicationProperties 加载失败,原因:{}",e.getMessage(),e);
			} finally{
				if(in!=null){
					try {
						in.close();
						in = null;
					} catch (IOException e) {
						Log.getLogger(PropertiesUtils.class).error("applicationProperties 关闭流失败，原因:{}",e.getMessage(),e);
					}
				}
			}
		}
		return applicationProperties;
	}
	public static String get(String key,String defaultValue){
		String value = getApplicationProperties().getProperty(key);
		if(StringUtils.isNotBlank(value))
			try {
				//Properties.load使用ISO859-1字符编码
				value = new String(value.getBytes("ISO8859-1"));
			} catch (UnsupportedEncodingException e) {
				Log.getLogger(PropertiesUtils.class).error("applicationProperties 转换编码失败，原因:{}",e.getMessage(),e);
			}
		return value;
	}
	public static String get(String key) {
		return get(key,null);
	}
}
